<template>
  <view class="confirm-page">
    <!-- 收货地址 -->
    <view class="address-box" @tap="changeAddress">
      <text class="default-mark" v-if="defaultAddress.isDefault === 1">默认</text>
      <text class="warn-mark" v-else>非默认</text>
      <text class="area-address">
        {{ defaultAddress.province + defaultAddress.city + defaultAddress.district }}
      </text>
      <p class="detail-address">{{ defaultAddress.detailAddress }}</p>
      <p class="accept-cellphone">{{ defaultAddress.receiverName }} {{ defaultAddress.receiverPhone }}</p>
      <text class="gt" decode="true">&gt;</text>
    </view>

    <!-- 商品容器 -->
    <view class="confirm-goods-container">
      <view v-if="selectedProduct" class="confirm-goods-item">
        <image :src="selectedProduct.image" mode="aspectFill" class="confirm-goods-image"></image>
        <view class="confirm-goods-info">
          <text class="goods-name">{{ selectedProduct.name }}</text>
          <text class="goods-price">￥{{ selectedProduct.price.toFixed(2) }}</text>
          <text class="goods-num">× {{ selectedProduct.num || 1 }}</text>
        </view>
      </view>

      <!-- 合计金额 -->
      <view class="total-row">
        <text class="total-text">合计：</text>
        <text class="total-amount">￥{{ totalPrice.toFixed(2) }}</text>
      </view>

      <!-- 支付按钮 -->
      <button class="pay-btn" @tap="handlePay">生成订单</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDefaultAddress  } from '@/api/Addressapi.js'
import { createOrder ,createOrderByProductId} from '@/api/Productapi.js'
import userManager from '@/common/utils/user.js'

// 默认地址
const defaultAddress = ref({
  addressId: null,
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: 0
})

// 选中的商品
const selectedProduct = ref(null)

onLoad((options) => {
  if (options.product) {
    try {
      selectedProduct.value = JSON.parse(decodeURIComponent(options.product))
    } catch (e) {
      console.error('解析商品数据失败:', e)
      uni.showToast({ title: '数据异常', icon: 'none' })
      setTimeout(() => uni.navigateBack(), 1500)
    }
  } else {
    uni.showToast({ title: '未选择商品', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})

onMounted(async () => {
  await loadDefaultAddress()
  uni.$on('addressChanged', loadDefaultAddress)
})

onUnmounted(() => {
  uni.$off('addressChanged', loadDefaultAddress)
})

const totalPrice = computed(() => {
  return selectedProduct.value ? selectedProduct.value.price * (selectedProduct.value.num || 1) : 0
})

const changeAddress = () => {
  uni.navigateTo({ url: '/pages/address/address' })
}

const handlePay = async () => {
  const user = userManager.user;
  if (!user || !user.userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
  const addressId = defaultAddress.value.addressId;
  console.log('addressId:',addressId);
  if (!addressId) {
    uni.showToast({ title: '请选择收货地址', icon: 'none' });
    return;
  }
  if (!selectedProduct.value) {
    uni.showToast({ title: '没有可支付的商品', icon: 'none' });
    return;
  }

  uni.showLoading({ title: '创建订单中...' });

  try {
	  console.log('selectedProduct.value.id',selectedProduct.value.id);
    const orderIds = await createOrderByProductId(
          user.userId,
          addressId,
          selectedProduct.value.id // 注意：确保 selectedProduct.value.id 是 productId
        );
    if (orderIds) {
      uni.hideLoading();
      console.log('完成下订单');
      // 可跳转到支付页或成功页
      uni.showToast({ title: '订单创建成功，跳转订单页中...', icon: 'success' });
	  uni.reLaunch({
	    url: `/pages/orders/orders`
	  });
	  
    }
  } catch (err) {
    uni.hideLoading();
    console.error('支付流程异常:', err);
    uni.showToast({ title: '下单失败，请重试', icon: 'none' });
  }
}

const loadDefaultAddress = async () => {
  try {
    const addr = await getDefaultAddress()
    if (addr) {
      defaultAddress.value = addr
    } else {
      uni.showToast({ title: '请先设置收货地址', icon: 'none' })
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/address/list' })
      }, 1000)
    }
  } catch (err) {
    console.error('加载地址失败:', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
  }
}
</script>

<style scoped>
/* 页面主容器 */
.confirm-page {
  background-color: #f8f8f8;
  padding: 30rpx;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 地址卡片 */
.address-box {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 40rpx;
  position: relative;
  overflow: hidden;
}

.default-mark {
  font-size: 24rpx;
  color: #e4393c;
  background-color: #ffebee;
  padding: 4rpx 10rpx;
  border-radius: 12rpx;
  margin-right: 10rpx;
}

.warn-mark {
  font-size: 24rpx;
  color: #999;
  background-color: #f0f0f0;
  padding: 4rpx 10rpx;
  border-radius: 12rpx;
  margin-right: 10rpx;
}

.area-address {
  font-size: 28rpx;
  color: #333;
  margin-top: 10rpx;
  line-height: 1.4;
}

.detail-address {
  font-size: 26rpx;
  color: #666;
  margin-top: 10rpx;
  line-height: 1.4;
}

.accept-cellphone {
  font-size: 26rpx;
  color: #333;
  margin-top: 10rpx;
  line-height: 1.4;
}

/* 修正箭头位置：使用绝对定位防止溢出 */
.gt {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  font-size: 40rpx;
  color: #999;
}

/* 商品容器 */
.confirm-goods-container {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 30rpx;
}

.confirm-goods-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.confirm-goods-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  object-fit: cover;
}

.goods-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
  word-break: break-all;
}

.goods-price {
  font-size: 28rpx;
  color: #e4393c;
  font-weight: bold;
}

.goods-num {
  font-size: 26rpx;
  color: #999;
  margin-left: 10rpx;
}

/* 总价行 */
.total-row {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 30rpx 0;
}

.total-text {
  font-size: 30rpx;
  color: #333;
  margin-right: 10rpx;
}

.total-amount {
  font-size: 36rpx;
  color: #e4393c;
  font-weight: bold;
}

/* 支付按钮 */
.pay-btn {
  width: 100%;
  background-color: #e4393c;
  color: white;
  font-size: 32rpx;
  font-weight: 500;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-top: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(228, 57, 54, 0.2);
  transition: background-color 0.2s ease;
  border: none;
  outline: none;
  box-sizing: border-box;
}

.pay-btn:active {
  background-color: #d82a2a;
}
</style>